/* Copyright (c) 2012 swing-on-fire Team
 * 
 * This file is part of Swing-On-Fire (http://code.google.com/p/swing-on-fire), licensed under the terms of the MIT
 * License (MIT).
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
package com.google.code.swingonfire.animation;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Semaphore;

import javax.swing.SwingUtilities;

/**
 * Runnable for the Swing Event Thread for parallel execution of all animations.
 * 
 * @author thred
 */
class AnimationRunnable implements Runnable
{

    private static class RunningAnimation
    {
        private final Animation animation;
        private final AnimationConsumer[] consumers;

        private double startTime = Double.NaN;
        private double lastTime = Double.NaN;
        private double nextTime = 0;

        public RunningAnimation(Animation animation, AnimationConsumer... consumers)
        {
            super();

            this.animation = animation;
            this.consumers = consumers;
        }

        private void animationReset(double time) throws AnimationException
        {
            startTime = lastTime = time;

            fireAnimationStarting();

            if (animation instanceof ResetableAnimation)
            {
                try
                {
                    ((ResetableAnimation) animation).animationReset();
                }
                catch (Exception e)
                {
                    throw new AnimationResetException(animation, "Invocation of animationReset caused exception", e);
                }
            }
        }

        public double animationStep(double time) throws AnimationException
        {
            if (Double.isNaN(nextTime))
            {
                throw new RuntimeException(
                    "Something went terribly wrong with handling animations (this if may be removed later, it's just for debugging)...");
            }

            if (Double.isNaN(startTime))
            {
                animationReset(time);
            }

            double delay = time - lastTime;

            lastTime = time;
            time = time - startTime;

            if (time < nextTime)
            {
                return nextTime - time;
            }

            double duration =
                (animation instanceof DurableAnimation) ? ((DurableAnimation) animation).getDuration() : Double.NaN;
            double fraction = AnimationUtil.toFraction(time, duration);

            fireAnimationBeforeStep(time, fraction);

            try
            {
                delay = AnimationUtil.animationResult(animation.animationStep(delay, time, fraction), time, duration);
            }
            catch (AnimationAbortedException e)
            {
                delay = Double.NaN;
            }
            catch (Exception e)
            {
                throw new AnimationStepException(animation, "Invocation of animationStep caused exception", e);
            }

            fireAnimationAfterStep(time, fraction);

            if (!AnimationUtil.isUndefined(duration))
            {
                if (duration == 0)
                {
                    delay = Double.NaN;
                }
                else
                {
                    if (time >= duration)
                    {
                        delay = Double.NaN;
                    }
                }
            }

            if (AnimationUtil.isFinished(delay))
            {
                animationFinished();
            }

            return delay;
        }

        private void animationFinished() throws AnimationConsumerException
        {
            fireAnimationFinished();

            nextTime = Double.NaN;
        }

        private void fireAnimationStarting() throws AnimationConsumerException
        {
            for (AnimationConsumer consumer : consumers)
            {
                if (consumer instanceof AnimationStartingConsumer)
                {
                    try
                    {
                        ((AnimationStartingConsumer) consumer).animationStarting(animation);
                    }
                    catch (Exception e)
                    {
                        throw new AnimationConsumerException(animation, consumer,
                            "Invocation of AnimationStartingConsumer caused exception", e);
                    }
                }
            }
        }

        private void fireAnimationBeforeStep(double time, double fraction) throws AnimationConsumerException
        {
            for (AnimationConsumer consumer : consumers)
            {
                if (consumer instanceof AnimationBeforeStepConsumer)
                {
                    try
                    {
                        ((AnimationBeforeStepConsumer) consumer).animationBeforeStep(animation, time, fraction);
                    }
                    catch (Exception e)
                    {
                        throw new AnimationConsumerException(animation, consumer,
                            "Invocation of AnimationBeforeStepConsumer caused exception", e);
                    }
                }
            }
        }

        private void fireAnimationAfterStep(double time, double fraction) throws AnimationConsumerException
        {
            for (AnimationConsumer consumer : consumers)
            {
                if (consumer instanceof AnimationAfterStepConsumer)
                {
                    try
                    {
                        ((AnimationAfterStepConsumer) consumer).animationAfterStep(animation, time, fraction);
                    }
                    catch (Exception e)
                    {
                        throw new AnimationConsumerException(animation, consumer,
                            "Invocation of AnimationAfterStepConsumer caused exception", e);
                    }
                }
            }
        }

        private void fireAnimationFinished() throws AnimationConsumerException
        {
            for (AnimationConsumer consumer : consumers)
            {
                if (consumer instanceof AnimationFinishedConsumer)
                {
                    try
                    {
                        ((AnimationFinishedConsumer) consumer).animationFinished(animation);
                    }
                    catch (Exception e)
                    {
                        throw new AnimationConsumerException(animation, consumer,
                            "Invocation of AnimationFinishedConsumer caused exception", e);
                    }
                }
            }
        }

    }

    private final Semaphore semaphore = new Semaphore(0);
    private final List<RunningAnimation> runningAnimations = new ArrayList<RunningAnimation>();

    private AnimationErrorHandler errorHandler;
    private double time;
    private double delay;

    /**
     * Creates the runnable
     */
    public AnimationRunnable()
    {
        super();
    }

    /**
     * Returns the error handler
     * 
     * @return the error handler
     */
    public AnimationErrorHandler getErrorHandler()
    {
        return errorHandler;
    }

    /**
     * Sets the error handler
     * 
     * @param errorHandler the error handler
     */
    public void setErrorHandler(AnimationErrorHandler errorHandler)
    {
        this.errorHandler = errorHandler;
    }

    /**
     * Executes the next iteration
     * 
     * @param time the time
     * @return the delay for the next iteration
     * @throws InterruptedException on occasion
     */
    public double execute(double time) throws InterruptedException
    {
        this.time = time;

        SwingUtilities.invokeLater(this);

        semaphore.acquire();

        return delay;
    }

    /**
     * Returns the current time
     * 
     * @return the time
     */
    public double getTime()
    {
        return time;
    }

    /**
     * Adds an animation, optionally with the specified {@link AnimationConsumer}s
     * 
     * @param animation the animation
     * @param consumers the consumers
     */
    public void addAnimation(Animation animation, AnimationConsumer... consumers)
    {
        removeAnimation(animation);
        runningAnimations.add(new RunningAnimation(animation, consumers));
    }

    /**
     * Removes the specified animation
     * 
     * @param animation the animation
     */
    public void removeAnimation(Animation animation)
    {
        Iterator<RunningAnimation> iterator = runningAnimations.iterator();

        while (iterator.hasNext())
        {
            if (iterator.next().animation.equals(animation))
            {
                iterator.remove();
            }
        }
    }

    /**
     * Removes all animations
     */
    public void clearAnimations()
    {
        runningAnimations.clear();
    }

    /**
     * Returns true if there is no animation running
     * 
     * @return true if empty
     */
    public boolean isAnimationsEmpty()
    {
        return runningAnimations.isEmpty();
    }

    /**
     * Executes the next step
     * 
     * @param time the time
     * @param errorHandler the error handler
     * @return the delay for the next step
     */
    public double animationStep(double time, AnimationErrorHandler errorHandler)
    {
        double minDelay = Double.NaN;
        Iterator<RunningAnimation> iterator = runningAnimations.iterator();

        while (iterator.hasNext())
        {
            RunningAnimation runningAnimation = iterator.next();
            double delay;

            try
            {
                delay = runningAnimation.animationStep(time);
            }
            catch (AnimationException e)
            {
                errorHandler.animationCausedException(e);
                delay = Double.NaN;
            }

            if (AnimationUtil.isFinished(delay))
            {
                iterator.remove();
            }
            else if ((Double.isNaN(minDelay)) || (delay < minDelay))
            {
                minDelay = delay;
            }
        }

        return minDelay;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void run()
    {
        delay = Double.NaN;

        try
        {
            delay = animationStep(time, errorHandler);
        }
        finally
        {
            semaphore.release();
        }
    }

}
